package com.lucas.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lucas.exception.MyException;
import com.lucas.mapper.AuthCodeMapper;
import com.lucas.pojo.Lagou_auth_code;
import com.lucas.service.AuthCodeService;
import com.lucas.service.EmailService;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.unit.DataUnit;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 **/
@Service
public class AuthCodeServiceImpl extends ServiceImpl<AuthCodeMapper, Lagou_auth_code> implements AuthCodeService{

    @Autowired
    private EmailService emailService;

    @Transactional(rollbackFor = MyException.class)
    @Override
    public boolean createAndSendCode(String email) {
        Date now = new Date();
        Lagou_auth_code lagouAuthCode = new Lagou_auth_code();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCreatetime(now);
        lagouAuthCode.setCode(RandomUtil.randomNumbers(5));
        //10 分钟有效
        lagouAuthCode.setExpiretime(DateUtil.offset(now, DateField.MINUTE,10));
        int insert = baseMapper.insert(lagouAuthCode);
        if(insert == 0){
            return false;
        }

        //发送邮箱
        boolean sendFlag = emailService.sendEmailWithCode(email, lagouAuthCode.getCode());
        if(!sendFlag){
            throw new MyException("发送验证码失败");
        }

        return true;
    }

    @Override
    public Integer validate(String email, String code) {
        Lagou_auth_code lagou_auth_code = new Lagou_auth_code();
        lagou_auth_code.setCode(code);
        lagou_auth_code.setEmail(email);
        QueryWrapper<Lagou_auth_code> queryWrapper = new QueryWrapper<>(lagou_auth_code);
        Lagou_auth_code result = baseMapper.selectOne(queryWrapper);
        if(result == null){
            return 1;
        }
        if(DateUtil.compare(new Date(),result.getExpiretime())>0){
            return 2;
        }

        return 0;
    }
}
